<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './branch.data';
  import { createBranch, editBranch, getBranchUserList } from '/@/api/system/system';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { getBranchList } from '/@/api/system/system';
  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false, maskClosable: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
          setFieldsValue({ manager: data.record.manager ? data.record.manager.split(',') : [] });
          const branchInnercode =
            data.record.parentInnercode === '0000'
              ? data.record.branchInnercode
              : data.record.parentInnercode;
          getBranchUserList({ branchInnercode: branchInnercode }).then((res) => {
            let data: any = [];
            res.forEach((val) => {
              data.push({ value: val.userName, label: val.realName });
            });
            // 回显机构管理员下拉数据
            updateSchema({
              field: 'manager',
              componentProps: {
                mode: 'multiple',
                options: data,
              },
            });
          });
        }
        const treeData = await getBranchList({ isSelect: 'Y' });
        updateSchema({
          field: 'parentInnercode',
          componentProps: ({ formActionType, formModel }) => {
            return {
              treeData,
              onChange: (value: any) => {
                // 根据机构来刷新机构管理员下拉框列表数据
                getBranchUserList({ branchInnercode: value }).then((res) => {
                  let data: any = [];
                  res.forEach((val) => {
                    data.push({ value: val.userName, label: val.realName });
                  });
                  const { updateSchema } = formActionType;
                  updateSchema({
                    field: 'manager',
                    componentProps: {
                      mode: 'multiple',
                      options: data,
                    },
                  });
                  formModel.manager = [];
                });
              },
            };
          },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (values.manager) {
            values.manager = values.manager.join();
          }
          if (unref(isUpdate)) {
            await editBranch(values);
            createMessage.success('机构修改成功');
          } else {
            await createBranch(values);
            createMessage.success('机构创建成功');
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
